package mywebapps.jsf;

import java.io.IOException;
import java.io.InputStream;

import javax.annotation.PostConstruct;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.inject.Named;

import mywebapps.dao.ArtProductDao;
import mywebapps.model.ArtProduct;

import org.apache.myfaces.custom.fileupload.UploadedFile;

@Named("addArtProductBean")
@RequestScoped
public class AddArtProductAction {
	private static final String UPLOAD_FAILED = "FAIL";
	private static final String UPLOAD_SUCCESS = "SUCCESS";
	
    private UploadedFile file;
    private String uploadResult;
    
    private ArtProduct artProduct;
    @Inject private ArtProductDao artProductDao;
    
    private String lastUploadedFile;
    
    @PostConstruct
    public void init() {
    	artProduct = new ArtProduct();
    }

	public ArtProduct getArtProduct() {
		return artProduct;
	}
	public void setArtProduct(ArtProduct artProduct) {
		this.artProduct = artProduct;
	}

	public void setArtProductDao(ArtProductDao artProductDao) {
		this.artProductDao = artProductDao;
	}

	public UploadedFile getFile() {
		return file;
	}
	public void setFile(UploadedFile file) {
		this.file = file;
	}
	
	public String getUploadResult() {
		return uploadResult;
	}

	public void setUploadResult(String uploadResult) {
		this.uploadResult = uploadResult;
	}

	public String getLastUploadedFile() {
		return lastUploadedFile;
	}
	
	
	public void upload() throws IOException {
		lastUploadedFile = artProduct.getFilename();
		
		InputStream stream = file.getInputStream();
		long size = file.getSize();
		byte[] buffer = new byte[(int)size];
		stream.read(buffer, 0, (int)size);
		stream.close();
		
		artProduct.setFilename(file.getName());
		artProduct.setImage(buffer);
		
		try {
		    artProductDao.createArtProduct(artProduct);
		    uploadResult = UPLOAD_SUCCESS;
		} catch(Exception e) {
			uploadResult = UPLOAD_FAILED;
			e.printStackTrace();
			return;
		}

		artProduct = new ArtProduct();
	}
}
